package com.abc.robot01.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.abc.robot01.R
import com.abc.robot01.activity.AddQAActivity
import com.abc.robot01.activity.ConfirmButton
import com.abc.robot01.activity.CustomStyledTextField
import com.abc.robot01.activity.LoadingDialog
import com.abc.robot01.activity.MYBLACK
import com.abc.robot01.activity.MYBLACK_Percent10
import com.abc.robot01.activity.MYBLACK_Percent5
import com.abc.robot01.activity.MYBLACK_Percent60
import com.abc.robot01.activity.MYBLUE
import com.abc.robot01.activity.MYRED
import com.abc.robot01.activity.MYWhilte_Percent40
import com.abc.robot01.activity.MyButton01
import com.abc.robot01.activity.MyFont_Size
import com.abc.robot01.activity.MyRoundedCornerShape
import com.abc.robot01.activity.MyRoundedCornerShape2
import com.abc.robot01.activity.SystemFragmentBackground
import com.abc.robot01.activity.px
import com.abc.robot01.activity.startActivity
import com.abc.robot01.databinding.Fragment03Binding
import com.abc.robot01.room.DatabaseContext
import com.abc.robot01.vivemodel.QAFragmentViewModel
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch

/**
 * A simple [Fragment] subclass as the default destination in the navigation.
 */
class QAFragment : Fragment() {

    val TAG = "QAFragment";

    private val viewModel: QAFragmentViewModel by viewModels()

    override fun onResume() {
        super.onResume()
        viewModel.getData()
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val composeView = ComposeView(requireContext()).apply {
            setContent {
                MaterialTheme {
                val name = remember {
                    mutableStateOf("")
                }

                SystemFragmentBackground {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(start = 30.px, top = 30.px),
                        verticalArrangement = Arrangement.Center,
//                  horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        MyButton01(
                            shape = RoundedCornerShape(10.px),
                            text = "新增语音配置",
                            containerColor = MYBLUE,
                            size = DpSize(244.dp / 3.5f, 50.dp / 3.5f)
                        ) {
                            this@QAFragment.requireContext().startActivity<AddQAActivity>()
                            Log.e(TAG, "" + it);
//                      show.value=true;
                        }
                        Spacer(modifier = Modifier.height(30.px))
                        Row {
                            BasicText(
                                text = "标题",
                                style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                                    fontSize = MyFont_Size,
                                    color = MYBLACK_Percent60
                                ),
                                modifier = Modifier.align(Alignment.CenterVertically)
                            )
                            Spacer(modifier = Modifier.width(20.px))
                            CustomStyledTextField(
                                placeHolder = "请输入",
                                search = false,
                                onValueChange = {
                                    name.value = it
                                })

                            Spacer(modifier = Modifier.width(30.px))
                            ConfirmButton(text = "查询") {
//                                viewModel.searcByQuestion(name.value);
                            }
                        }
                        Spacer(modifier = Modifier.height(30.px))
                        Header();
                        DataList(::edit, ::delete);
                    }
                    val loading = remember { viewModel.loading }
                    LoadingDialog(loading)
                }

            }
        }
            }
        return composeView
    }

    private fun edit(id: Int) {
    }

    private fun delete(id: Long) {
        lifecycleScope.launch(IO) {
            DatabaseContext.getCmdDao().deleteById(id)
            DatabaseContext.getChatQuestionDao().deleteByCmdId(id.toString())
            DatabaseContext.getChatAnswerDao().deleteByCmdId(id.toString())
        }
    }

    @Composable
    fun Header() {
        Surface(
            modifier = Modifier
                .background(Color(0x00333333))
                .width(1600.px)
                .height(
                    56.px
                ),
            color = MYBLACK_Percent5,
            shape = MyRoundedCornerShape

        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.padding(start = 30.px)
            ) {
                BasicText(
                    text = "ID",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = Color.Black
                    ),
                )
                Spacer(modifier = Modifier.width(87.px))

                BasicText(
                    text = "标题",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = Color.Black
                    ),
                )
                Spacer(modifier = Modifier.width(422.px))
                BasicText(
                    text = "创建时间",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = Color.Black
                    ),
                )
                Spacer(modifier = Modifier.width(625.px))
                BasicText(
                    text = " 操作",
                    style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                        fontSize = MyFont_Size,
                        color = Color.Black
                    ),
                )
            }
        }
    }

    data class DataA(
        var question: String = "",
        var date: String = "",
        var cmdId: Long = 0
    )

    @Composable
    fun DataList(edit: (id: Int) -> Unit = { }, delete: (id: Long) -> Unit = { }) {
        Log.e(TAG,"DataList");
        val items = viewModel.items.collectAsState()
        LazyColumn(
            modifier = Modifier
                .width(1600.px)
                .background(Color.Transparent)
        ) {
            itemsIndexed(items.value) { index, item ->
                Log.e(TAG,"itemsIndexed "+item);
                val isLastItem = index == items.value.lastIndex
                //不能使用row的原因是修改时间要和title对齐.
                Box(
                    modifier = Modifier
                        .padding(start = 0.px)
                        .height(90.px)
                        .width(1600.px)
                        .background(
                            color = MYWhilte_Percent40, // 背景颜色
                            shape = if (isLastItem) MyRoundedCornerShape2 else RoundedCornerShape(0)
                        )
                ) {
                    BasicText(
                        modifier = Modifier.offset(30.px, 33.px),
                        text = "" + (index+1),
                        style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = Color.Black
                        ),
                    )

                    BasicText(
                        modifier = Modifier.offset(140.px, 33.px),
                        text = item.question,
                        style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )
                    BasicText(
                        modifier = Modifier.offset(612.px, 33.px),
                        text = item.date,
                        style = TextStyle(
//                          fontWeight = FontWeight.Bold,
                            fontSize = MyFont_Size,
                            color = MYBLACK
                        ),
                    )

                    MyButton01(
                        shape = RoundedCornerShape(8.px),
                        modifier = Modifier.offset(x = 1334.px, y = 21.px),
                        text = "编辑",
                        containerColor = MYBLUE,
                        size = DpSize(108.px, 48.px)
                    ) {
                        this@QAFragment.requireContext().startActivity<AddQAActivity> {
                            putExtra("cmd_id", item.cmdId)
                        }
                        edit(index)
                    }
                    MyButton01(
                        shape = RoundedCornerShape(8.px),
                        modifier = Modifier.offset(x = 1462.px, y = 21.px),
                        text = "删除",
                        containerColor = MYRED,
                        size = DpSize(108.px, 48.px)
                    ) {
                        items.value.removeAt(index)
                        delete(item.cmdId)
                    }
                }
                if (isLastItem.not())
                    HorizontalDivider(
                        modifier = Modifier.fillMaxWidth(),
                        thickness = 1.dp / 3.5f,
                        color = MYBLACK_Percent10
                    )
            }
        }
    }
}